using System.Collections.Generic;
using ProtoModels;

public class OwnedItems
{
	public static string DefaultOwnedItemsFilename = "ownedItems.bytes";

	private OwnedItemsDAO ownedItems;

	public string OwnedItemsFilename { get; private set; }

	public OwnedItems(string filename)
	{
		OwnedItemsFilename = filename;
		ReloadModel();
	}

	public void ReloadModel()
	{
		if (!ProtoIO.LoadFromFile<ProtoSerializer, OwnedItemsDAO>(OwnedItemsFilename, GGFileIO.instance, out ownedItems))
		{
			ownedItems = new OwnedItemsDAO();
			ProtoIO.SaveToFile(OwnedItemsFilename, ownedItems);
		}
		if (ownedItems.ownedItems == null)
		{
			ownedItems.ownedItems = new List<OwnedItemDAO>();
			ProtoIO.SaveToFile(OwnedItemsFilename, ownedItems);
		}
	}

	public void addToOwned(string name, bool canStockpile)
	{
		if (canStockpile || !isOwned(name))
		{
			OwnedItemDAO ownedItemDAO = new OwnedItemDAO();
			ownedItemDAO.name = name;
			ownedItems.ownedItems.Add(ownedItemDAO);
			Save();
		}
	}

	public void RemoveOneItemFromOwned(string name)
	{
		foreach (OwnedItemDAO ownedItem in ownedItems.ownedItems)
		{
			if (ownedItem.name == name)
			{
				ownedItems.ownedItems.Remove(ownedItem);
				Save();
				break;
			}
		}
	}

	public bool isOwned(string name)
	{
		OwnedItemDAO ownedItemDAO = ownedItems.ownedItems.Find((OwnedItemDAO o) => o.name == name);
		return ownedItemDAO != null;
	}

	public int GetNumberOfItemsOwned(string name)
	{
		int num = 0;
		foreach (OwnedItemDAO ownedItem in ownedItems.ownedItems)
		{
			if (ownedItem.name == name)
			{
				num++;
			}
		}
		return num;
	}

	public void Save()
	{
		ProtoIO.SaveToFileCloudSync(OwnedItemsFilename, ownedItems);
	}
}
